<template>
  <Layout>
    <div>
    <el-row class="el-row">
      <div class="el-col">
        <el-select filterable v-model="goodsTraderId" placeholder="" size="small" style="width: 150px">
          <el-option v-for="{text,goodsTraderId} in goodList" :key="goodsTraderId" :label="text" :value="goodsTraderId" class="option_text">
          </el-option>
        </el-select>
      </div>
    </el-row>
  </div>
  <div :id="chartId" class="k-line-chart" ref="chart"/>
 </Layout>
</template>

<script>
import { init} from "klinecharts";
import { mapActions,mapState } from 'pinia';
import { crosshair,charts,currentChartId,originCrosshair } from '../../store.js'
import Layout from "./Layout.vue";
import '../../klinechartOverlay.js'


export default {
  name: "testBackChartOverlay",
  components: { Layout },
  props:{
    id:{type:String,default:() => (`chart_${Math.ceil(Math.random() * 999999)}`)},
    union:{type:Boolean,default:false},
    goodList:{type:Array},
    rate:{type:Number},
    currentSize:{type:Number},
  },
  data: function () {
    return {
      goodsTraderId:undefined,
      currentGoodInfo:undefined,
      chart:undefined, //表格对象
      volFlg:false,//防止重复开启交易量
      // loading:false,//加载状态
      currentLineList:[], //当前的k线数据
      // lineList:[],//k线数据
      // currentLineLength:0, //现在的k线位置
      // execTime:0, // 执行的时间
    };
  },
  mounted: async function () {
    this.createChart(); //创建表格
  },
  computed:{
    chartId(){
    return `${this.id}_pkid`;
    },
    ...mapState(originCrosshair, ['originCrosshair']),
  },
  watch:{
    goodsTraderId(newVal){
      if(newVal){
        this.currentLineList = [];
        this.removeChart();
        this.currentGoodInfo = this.goodList.find(v => v.goodsTraderId == newVal);
        this.chart.setTimezone(this.currentGoodInfo.lineInfo.timezone); //设置时区
        if(this.union){
          //联动
          this.addCharts(this.chart);
          this.chart.onHandviorMoused = (crosshair) => {
          //获取point对应的时间等数据
          if(crosshair){
            this.setoriginCrosshair(JSON.parse(JSON.stringify(crosshair)));
          }
          else{
            this.setoriginCrosshair(crosshair);
          }
          if(crosshair){
            crosshair = this.chart.getChartStore().getCrosshairStore().getData(crosshair);
          }
            this.setCrosshair(crosshair);
            this.setCurrentChartId(this.chart.id)
          };
        }
        this.setKLine();
      }
    },
    currentSize(newVal,oldVal){
      if(newVal != oldVal && this.currentGoodInfo){
        if(newVal == 0){
          this.currentLineList = [];
          this.chart.clearData();
        }
        this.setKLine();
      }
    }
  },
  methods: {
    ...mapActions(crosshair,{setCrosshair:'set'}),
    ...mapActions(originCrosshair,{setoriginCrosshair:'set'}),
    ...mapActions(charts,{addCharts:'add',removeCharts:'remove'}),
    ...mapActions(currentChartId,{setCurrentChartId:'set'}),
    async createChart(){
      this.chart = init(this.chartId,{});
      this.chart.setLocale('zh-CN'); //设置为中文
      this.chart.setPriceVolumePrecision(4); //设置价格精度
      this.chart.setStyles({
        grid: {
          show: true,
          horizontal: {
            // color:'#434447',
            color:'#3B3C3E',
          },
          vertical: {
            show: true,
            size: 1,
            color: '#FFFFFF',
            style: 'dashed',
            dashedValue: [2, 2]
          }
        },
        candle:{
          bar:{
            upColor: '#F92855',
            downColor: '#2DC08E',
            upBorderColor: '#F92855',
            downBorderColor: '#2DC08E',
            upWickColor: '#F92855',
            downWickColor: '#2DC08E',
          },
          tooltip: {
            text: {
              color: '#FFFFFF',
            },
          },
          priceMark: {
              high: {
                show: true,
                // color: '#FFFFFF',
                color: 'transparent',
              },
              // 最低价标记
              low: {
                show: true,
                // color: '#FFFFFF',
                color: 'transparent',
              },
          }
        },
        xAxis:{
          // // x轴线
          // axisLine: {
          //   color: '#888888',
          // },
          // x轴分割文字
          tickText: {
            color: '#FFFFFF',
          },
        },
        yAxis:{
          tickText: {
            color: '#FFFFFF',
          },
        },
        indicator: {
          ohlc: {
            upColor: 'rgba(249, 40, 85, .7)',
            downColor: 'rgba(45, 192, 142, .7)',
          },
          bars: [{
            upColor: 'rgba(249, 40, 85, .7)',
            downColor: 'rgba(45, 192, 142, .7)',
          }],
          tooltip: {
            text: {
              color: '#FFFFFF',
            },
          }
        }
      }); //设置价格精度
      if(!this.volFlg){
        this.chart.createIndicator({name:'VOL',isStack:true}); //开启交易量
        this.volFlg = true;
      }
      // if(this.union){
      //   //联动
      //   this.addCharts(this.chart);
      //   this.chart.onHandviorMoused = (crosshair) => {
      //   // if(!this.currentLineList.length) return;
      //   //获取point对应的时间等数据
      //   if(crosshair){
      //     crosshair = this.chart.getChartStore().getCrosshairStore().getData(crosshair);
      //   }
      //     this.setCrosshair(crosshair);
      //     this.setCurrentChartId(this.chart.id)
      //   };
      // }

      //添加监听Dom变化
      const myObserver = new ResizeObserver((entries) => {
        entries.forEach((entry) => {
          this.chart.adjustPaneViewport(true, true, true, true, true);
        })
      })
      myObserver.observe(this.$refs.chart);
    },
    // applyKLine(){
    //   let lineSize = this.lineList.length;
    //   let totalTime = (1 * 60 * 1000) / this.rate; //总时间
    //   let lineStep = 0,stepTime;
    //   // lineStep = Math.ceil(lineSize / totalTime); //每次显示的k线数量
    //   do{
    //     lineStep++;
    //     stepTime = parseInt((totalTime / Math.ceil(lineSize / lineStep)).toFixed(0)); //步进时间
    //     stepTime =(stepTime - this.execTime > 0 ?(stepTime - this.execTime): 0);
    //   }
    //   while(stepTime < 50);

    //   let currentGoodsTraderId = this.goodsTraderId;
    //   // console.log(currentGoodsTraderId);
    //   setTimeout(() => {
    //     //是否还在这个周期
    //     if(currentGoodsTraderId == this.goodsTraderId){
    //       let startDate = Date.now();
    //       //是否已经显示完成
    //       if(this.currentLineLength == this.lineList.length){
    //         return;
    //       }
    //       this.currentLineLength += lineStep;
    //       if(this.currentLineLength > this.lineList.length){
    //         this.currentLineLength = this.lineList.length;
    //       }
    //       this.chart.applyNewData(this.lineList.slice(0,this.currentLineLength));
    //       this.applyKLine();
    //       let endDate = Date.now();
    //       this.execTime = endDate - startDate;
    //       // this.$emit('getCurrentLine',{
    //       //   goodInfo:this.currentGoodInfo,
    //       //   goodsTraderId:this.goodsTraderId,
    //       //   line:this.lineList.slice(this.currentLineLength - 1,this.currentLineLength),
    //       //   isEnd: this.currentLineLength == this.lineList.length,
    //       //   chartId:this.id
    //       // });
    //     }
    //   },stepTime);
    // },
    setKLine(){
      let maxSize = this.currentGoodInfo.lineInfo.totalSize;
      let lineList = this.currentGoodInfo.lineInfo.lineList;
      let size;
      if(this.currentLineList.length == maxSize) return;
      if(this.currentSize >= maxSize){
        size = maxSize;
      }
      else{
        size = this.currentSize;
      }
      if(this.currentLineList.length == 0){
        //第一次加载
        this.currentLineList = lineList.slice(0,size);
        this.chart.applyNewData(this.currentLineList);
      }
      else {
        let oldSize = this.currentLineList.length;
        this.currentLineList = lineList.slice(0,size);
        let newSize = this.currentLineList.length;
        if(newSize -  oldSize >= 3){
          //快进
          this.chart.applyNewData(this.currentLineList);
        }
        else{
          this.currentLineList.slice(oldSize,newSize).forEach(v => {
            this.chart.updateData(v);
          });
        }
      }
    },
    removeChart(){
      // console.log('removeChart');
      if(this.union) this.removeCharts(this.chart);
      if(this.chart) this.chart.clearData();
    },
  },
  unmounted: function () {
    this.removeChart();
  },
};
</script>
<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.k-line-chart {
  width: 100%;
  flex-grow: 1;
  overflow: hidden;
}
.el-row{
  margin-bottom: 10px;
}
.el-col{
  margin-right: 20px;
}
.el-icon-close{
  padding: 0px 8px;
  line-height:100%;
  height:100%;
}
.option_item{
  display: flex;
  width: 100%;
}
.option_text{
  flex-grow: 1;
}
.option_icon{

}
.option_icon_start_filled{
  padding: 0px 11px;
  line-height:100%;
  height:100%;
}
.option_icon_start{
  padding: 0px 15px;
  line-height:100%;
  height:100%;
}
</style>